package com.eastfair.imaster.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.eastfair.api.QuestionnaireServiceFeign;
import com.eastfair.core.jackson.JsonUtil;
import com.eastfair.core.utils.ApacheHttpClientsUtils;
import com.eastfair.core.utils.StringUtils;
import com.eastfair.enums.SystemSourceEnum;
import com.eastfair.imaster.dto.VisitorRegisterDTO;
import com.eastfair.imaster.dto.VisitorRegisterStateDTO;
import com.eastfair.imaster.entity.VisitorPushRequest;
import com.eastfair.imaster.entity.VisitorPushResponse;
import com.eastfair.imaster.entity.VisitorPushResponseBaoli;
import com.eastfair.imaster.entity.VisitorRegisterState;
import com.eastfair.imaster.enumeration.BZTSourceEnum;
import com.eastfair.imaster.service.VisitorRegisterPushService;
import com.eastfair.imaster.service.VisitorRegisterStateService;
import com.eastfair.projectcore.api.ProjectCoreServiceFeign;
import com.eastfair.core.snowflake.DefaultUidGenerator;
import com.eastfair.questionnaire.dto.AnswerSubjectResultSaveDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Date:2021/8/24
 * Time:11:19
 *
 * @author zjn
 */
@Slf4j
@Service
@DS("#thread.tenant")
public class VisitorRegisterPushServiceImpl implements VisitorRegisterPushService {

    @Autowired
    private ProjectCoreServiceFeign projectCoreServiceFeign;
    @Autowired
    private VisitorRegisterStateService visitorRegisterStateService;
    @Autowired
    private QuestionnaireServiceFeign questionnaireServiceFeign;

    @Override
    public void pushVisitor(VisitorRegisterDTO visitorRegisterDTO, VisitorRegisterStateDTO visitorRegisterStateDTO, AnswerSubjectResultSaveDTO answerSubjectResultSaveDTO) {
        VisitorPushRequest visitorPushRequest = getVisitorPushRequest(visitorRegisterDTO);
        // TODO 同步问卷
//        visitorPushRequest.setAns();
        String json = null;
        try {
            json = "[" + JsonUtil.entityToJsonReplaceNull(visitorPushRequest) + "]";
        } catch (IOException e) {
            log.error("同步SQLServer数据转换异常：" + visitorPushRequest.toString());
        }
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("exhid", projectCoreServiceFeign.getExhibitionById(visitorRegisterDTO.getExhibitionId()).getData().getExhId() + "");
        paramMap.put("source", SystemSourceEnum.IMASTER.getCode());
        paramMap.put("data", json);
        log.info("同步SQLServer请求值：" + paramMap.toString());
        String result = ApacheHttpClientsUtils.postForm("https://api.exporegist.com/common/api/visitor/SyncVisitor", paramMap);
        log.info("同步SQLServer返回值：" + result);
        result = StringEscapeUtils.unescapeJava(result);
        VisitorPushResponse visitorPushResponse = JsonUtil.parse(result, VisitorPushResponse.class);
        if (visitorPushResponse.getStatus() != 1) {
            log.error("同步SQLServer异常：" + result);
            throw new RuntimeException("同步SQLServer异常");
        }
        String[] personArray = visitorPushResponse.getData().split(":");
        if (personArray.length < 3) {
            log.error("同步SQLServer异常：" + result);
            throw new RuntimeException("同步SQLServer异常");
        }
        // 获取同步观众id 以及 胸牌卡号
        updateSyncById(personArray[1], personArray[2], visitorRegisterStateDTO);
    }

    @Override
    @Async
    public void pushVisitorBaoLi(VisitorRegisterDTO visitorRegisterDTO, VisitorRegisterStateDTO visitorRegisterStateDTO, String assistVisitorCardNumber, AnswerSubjectResultSaveDTO answerSubjectResultSaveDTO) {
        Map<String, String> paramMap = new HashMap<>();
        // 个人信息
        paramMap.put("id", String.valueOf(visitorRegisterDTO.getId()));
        paramMap.put("PsjVisitorCard", visitorRegisterStateDTO.getCardNumber());
        paramMap.put("PsnEmail", visitorRegisterDTO.getEmail());
        paramMap.put("PsnGender", visitorRegisterDTO.getGender());
        paramMap.put("PsnName", visitorRegisterDTO.getName());
        paramMap.put("PsnRank", visitorRegisterDTO.getPost());
        paramMap.put("PsnDept", visitorRegisterDTO.getDepartment());
        paramMap.put("PsnCountry", projectCoreServiceFeign.getAreaById(visitorRegisterDTO.getCountryId()).getData().getName());
        paramMap.put("PsnProvince", projectCoreServiceFeign.getAreaById(visitorRegisterDTO.getProvinceId()).getData().getName());
        paramMap.put("PsnCity", projectCoreServiceFeign.getAreaById(visitorRegisterDTO.getCityId()).getData().getName());
        paramMap.put("PsnAddress", visitorRegisterDTO.getAddress());
        paramMap.put("PsnIDCard", visitorRegisterDTO.getIdentificationNumber());
        paramMap.put("PsnOtherLinkInfo", visitorRegisterDTO.getSocialMedia());
        paramMap.put("PsnHeadUrl", visitorRegisterDTO.getHeadImageUrl());
        paramMap.put("PsnCredentialUrl", visitorRegisterDTO.getWorkPassUrl());
        paramMap.put("PsnWorkCardUrl", visitorRegisterDTO.getCompanyRegistrationUrl());
        paramMap.put("PsnComName", visitorRegisterDTO.getCompanyName());

        // 电话区号
        String phoneCode = projectCoreServiceFeign.getPhoneCodeByAreaId(visitorRegisterDTO.getCountryId()).getData();
        if (!StringUtils.isBlank(phoneCode) && !StringUtils.isBlank(visitorRegisterDTO.getTelephone())) {
            paramMap.put("PsnTel", phoneCode + "-" + visitorRegisterDTO.getTelephone());
        } else if (!StringUtils.isBlank(visitorRegisterDTO.getTelephone())) {
            paramMap.put("PsnTel", visitorRegisterDTO.getTelephone());
        }
        if (!StringUtils.isBlank(phoneCode) && !StringUtils.isBlank(visitorRegisterDTO.getMobile())) {
            paramMap.put("PsnMobile", phoneCode + "-" + visitorRegisterDTO.getMobile());
        } else if (!StringUtils.isBlank(visitorRegisterDTO.getMobile())) {
            paramMap.put("PsnMobile", visitorRegisterDTO.getMobile());
        }

        if (!StringUtils.isBlank(assistVisitorCardNumber)) {
            paramMap.put("InvitCardNo", assistVisitorCardNumber);
        }

        String country = visitorRegisterDTO.getCountryId() + "";
        if (country.equals(BZTSourceEnum.INSIDE.getCode())) {
            paramMap.put("RegistType", BZTSourceEnum.INSIDE.getName());
        } else {
            paramMap.put("RegistType", BZTSourceEnum.OUTSIDE.getName());
        }
        paramMap.put("VisitorID", visitorRegisterStateDTO.getSyncVisitorId() + "");

        // 总部公司信息
        paramMap.put("ComAddress", visitorRegisterDTO.getHeadquartersAddress());
        paramMap.put("ComTel", visitorRegisterDTO.getHeadquartersTelephone());
        paramMap.put("ComFax", visitorRegisterDTO.getHeadquartersFax());
        paramMap.put("ComCountry", projectCoreServiceFeign.getAreaById(visitorRegisterDTO.getHeadquartersCountryId()).getData().getName());

        paramMap.put("PsnZipCode", visitorRegisterDTO.getZipCode());
        paramMap.put("ComZipCode", visitorRegisterDTO.getCompanyZipCode());
        paramMap.put("ComBrand", visitorRegisterDTO.getCompanyBrand());


        // TODO 同步问卷
//        paramMap.put("Answers", convertAnswerResultToExternal(answerSubjectResultSaveDTO));

        paramMap.put("Key", "BljhVisitorReg2018");
        paramMap.put("ExhID", projectCoreServiceFeign.getExhibitionById(visitorRegisterDTO.getExhibitionId()).getData().getExhId() + "");

        //调用接口将数据传递到SQL，并获得回传的数据
        String postUrl = "http://14.23.50.68:23380/EFWebService/api/EfWebService/RegistPersonWiCardNo";
        String result = ApacheHttpClientsUtils.postForm(postUrl, paramMap);
        log.info("保利同步SQLServer返回值：" + result);
        result = StringEscapeUtils.unescapeJava(result);
        result = result.substring(1, result.length() - 1);
        VisitorPushResponseBaoli visitorPushResponse = JSON.parseObject(result, VisitorPushResponseBaoli.class);
        if (!"OK".equals(visitorPushResponse.getStatus()) || StringUtils.isBlank(visitorPushResponse.getMsg())) {
            log.error("保利同步SQLServer异常：" + result);
            throw new RuntimeException("保利同步SQLServer异常");
        }
        log.info("保利生成同步id：" + visitorPushResponse.getMsg());
        updateSyncById(visitorPushResponse.getMsg(), null, visitorRegisterStateDTO);

    }


    /**
     * 展立方同步数据转换
     *
     * @param visitorRegisterDTO 预登记数据
     * @return 展立方同步数据转换类
     */
    private VisitorPushRequest getVisitorPushRequest(VisitorRegisterDTO visitorRegisterDTO) {
        VisitorPushRequest visitorPushRequest = new VisitorPushRequest();
        visitorPushRequest.setName(visitorRegisterDTO.getName());
        visitorPushRequest.setEmail(visitorRegisterDTO.getEmail());
        visitorPushRequest.setMobile(visitorRegisterDTO.getMobile());
        visitorPushRequest.setAddress(visitorRegisterDTO.getAddress());
        visitorPushRequest.setCity(projectCoreServiceFeign.getAreaById(visitorRegisterDTO.getCityId()).getData().getName());
        visitorPushRequest.setProvince(projectCoreServiceFeign.getAreaById(visitorRegisterDTO.getProvinceId()).getData().getName());
        visitorPushRequest.setCountry(projectCoreServiceFeign.getAreaById(visitorRegisterDTO.getCountryId()).getData().getName());
        visitorPushRequest.setComName(visitorRegisterDTO.getCompanyName());
        visitorPushRequest.setRank(visitorRegisterDTO.getPost());
        visitorPushRequest.setTel(visitorRegisterDTO.getTelephone());
        visitorPushRequest.setFaceUrl(visitorRegisterDTO.getFaceImageUrl());
        visitorPushRequest.setIdCard(visitorRegisterDTO.getIdentificationNumber());
        return visitorPushRequest;
    }

    /**
     * 根据预登记状态id修改同步观众id
     *
     * @param syncVisitorId           同步观众id
     * @param visitorRegisterStateDTO 预登记状态
     */
    private void updateSyncById(String syncVisitorId, String cardNumber, VisitorRegisterStateDTO visitorRegisterStateDTO) {
        VisitorRegisterState visitorRegisterState = new VisitorRegisterState();
        visitorRegisterState.setSyncVisitorId(syncVisitorId);
        visitorRegisterState.setId(visitorRegisterStateDTO.getId());
        visitorRegisterState.setAuditState(visitorRegisterStateDTO.getAuditState());
        if (!StringUtils.isBlank(cardNumber)) {
            visitorRegisterState.setCardNumber(cardNumber);
        }
        visitorRegisterStateService.saveOrUpdate(visitorRegisterState);
    }

}
